
import { colWrapper } from '../colWrapper'
import enums from '@/views/workflow/utils/enum'

export function tableHtml(element, confGlobal) {
  const fieldName = element.vModel || `table${element.formId}`
  const data = `:data="${confGlobal.formModel}['${fieldName}']"`
  // const loading = `${fieldName}loading`
  const height = element.height ? `height="${element.height}"` : ''
  const maxHeight = element.maxHeight ? `max-height="${element.maxHeight}"` : ''
  const stripe = element.stripe ? `:stripe=${element.stripe}` : ''
  const border = element.border ? `:border=${element.border}` : ''
  const size = element.size ? `size="${element.size}"` : ''
  const fit = element.fit ? `:fit="${element.fit}"` : ''
  const showHeader = element.showHeader ? `:show-header="${element.showHeader}"` : ''
  const highlightCurrentRow = element.highlightCurrentRow ? `:highlight-current-row="${element.highlightCurrentRow}"` : ''
  const currentRowKey = element.currentRowKey ? `current-rowKey="${element.currentRowKey}"` : ''
  const showSummary = element.showSummary ? 'show-summary' : ''

  // 表格可编辑条件：属性设置为可编辑且表单没设置禁用且页面没设置禁用
  const editable = element.editable && !confGlobal.disabled && !confGlobal.disabledAll

  const columnsHtml = []
  const summaryColumns = [] // 需要合计的列索引
  getColumnHtml(element, editable, columnsHtml, summaryColumns)

  // 如果设置了数据选择SQL则可以选择并添加行
  const btnSelect = element.valueData ? 
  `<el-button type="primary" size="mini" 
  @click="handle${element.componentName}Select">选择并添加行</el-button>
  ` : ''
  const toolBar = editable ? `
    <div style="padding: 10px; border: 1px solid #EBEEF5; border-bottom: 0; text-align: right;">
      ${btnSelect}\n
      <el-button type="primary" size="mini" @click="handle${element.componentName}Add()">添加空行</el-button>
    </div>
  ` : ''

  const summaryMethod = `:summary-method="(param) => {
    const { columns, data } = param
    const sums = []
    columns.forEach((column, index) => {
      // if (index === 0) {
      //   sums[index] = '合计'
      //   return
      // }
      const values = data.map(item => Number(item[column.property]))
      if ('${summaryColumns.join(',')}'.split(',').indexOf(column.property) >=0 && !values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0);
        sums[index]
      } else {
        sums[index] = ''
      }
    });
    return sums
  }"`

  const desision = element.isDecision ? `
    <div style="padding: 10px; border: 1px solid #EBEEF5; border-bottom: 0;">
    <el-button type="danger" plain size="small" icon="el-icon-warning" v-show="!decisionTips.show" @click="() => {
      this.decisionTips.show = true
    }">显示辅助决策提示</el-button>
    <el-alert
      v-show="decisionTips.show"
      title="提示"
      close-text="隐藏"
      :description="decisionTips.msg"
      type="error"
      show-icon
      @close="() => {
        this.decisionTips.show = false
        this.$set(this.decisionTips, 'show', false)
      }">
    </el-alert>
    </div>
  ` : ''

  let str = `
    <div style="margin-bottom: 22px;">
      ${toolBar}
      ${desision}
      <el-table 
      ref="${element.componentName}" 
      ${data} 
      ${height} 
      ${maxHeight}
      ${stripe} 
      ${border} 
      ${size} 
      ${fit} 
      ${showHeader} 
      ${highlightCurrentRow} 
      ${currentRowKey} 
      ${showSummary}
      ${summaryMethod}
      style="width: 100%; overflow: visible;"
      class="detail-table"
      @current-change="handle${element.componentName}CurrentChange"
      @selection-change="handle${element.componentName}SelectionChange"
      :row-class-name="({row, rowIndex}) => {
        if (${element.isDecision} && row.comparisonMessage) { // 如果开启了辅助决策，且有行提示则改变改行的背景色
          return 'table-row-warning'
        } else {
          return ''
        }
      }"
      >
        ${columnsHtml.join('\n')}
      </el-table>
    </div>        
  `
  str = colWrapper(element, str)
  return str
}

// 获得表格列的html
function getColumnHtml(element, editable, columnsHtml, summaryColumns) {
  if (element.columns && element.columns.length > 0) {
    if (element.isDecision) { // 如果该子表开启了辅助决策，则自动添加一个特殊列用于冒泡查看提示信息
      const comparisonMessageCol = {
        label: '',
        prop: 'comparisonMessage',
        width: '60px',
        fixed: true,
        align: 'center'
      }
      element.columns.splice(0, 0, comparisonMessageCol)
    }
    element.columns.forEach((column, index)=> {
      const type = column.type ? `type="${column.type}"` : ''
      const columnKey = column.columnKey ? `column-key="${column.columnKey}"` : ''
      const label = column.label ? `label="${column.label}"` : ''
      const prop = column.prop ? `prop="${column.prop}"` : ''
      const width = column.width ? `width="${column.width}"` : ''
      const minWidth = column.minWidth ? `min-width="${column.minWidth}"` : ''
      const showOverflowTooltip = column.showOverflowTooltip ? `:show-overflow-tooltip="${column.showOverflowTooltip}"` : ''
      const visible = column.visible === false ? `v-if="false"` : ''
      const fixed = column.fixed ? `fixed` : ''
      const sortable = column.sortable ? `sortable` : ''
      const resizable = column.resizable ? `resizable` : ''
      const align = column.align ? `align="${column.align}"` : ''
      const headerAlign = column.headerAlign ? `header-align="${column.headerAlign}"` : ''
      if (column.showSummary) {
        summaryColumns.push(column.prop)
      }
      let className = ''
      let tagDom = ''
      if (Object.keys(enums.TAB_COLUMN_TTYPE)[2] === column.type && tags[column.tag]) { // 可编辑，且该列为组件列，则渲染组件
        // column.component.vModel = `scope.row.${column.prop}` // 列里面的组件vModel改成scope.row.prop
        column.component.table = {
          tableName: element.componentName,
          prop: column.prop
        } // 将列对应的字段传入，在指定select等组件列的option时，用于双向绑定

        // fieldName为el-table的数据源字段，也即el-form绑定的model对应的el-table的prop
        // 如el-form的model为form，el-table的数据源为form.tableData，那么fieldName则为tableData
        tagDom = `
        <template slot-scope="scope">
          <el-form-item label-width="0px" :prop="'${fieldName}.'+scope.$index+'.${column.prop}'" :rules="rules['${element.componentName}']['${column.prop}']">
            ${tags[column.tag](column.component)}
          </el-form-item>
        </template>
        `
      }
      if (['dept-select', 'dept-position-s', 'dept-user-s'].indexOf(column.tag) >= 0) {
        className = 'class-name="org-table-cell"'
      }

      // 辅助决策
      if (column.prop === 'comparisonMessage') {
        tagDom = `
        <template slot-scope="scope">
          <template v-if="scope.row.comparisonMessage">
            <el-popover
              placement="top-start"
              title="提示"
              width="200"
              trigger="hover"
              :content="scope.row.comparisonMessage">
                <van-icon name="warning-o" style="color: #F56C6C"/>
            </el-popover>
          </template>
        </template>
        `
      }

      columnsHtml.push(`<el-table-column ${type} ${columnKey} ${label} ${prop} ${width} ${minWidth} ${className} ${showOverflowTooltip} ${visible} ${fixed} ${sortable} ${resizable} ${headerAlign} ${align} style="overflow: visible;">
        ${tagDom}
        </el-table-column>`
      )
    })
    getOptHtml(element, editable, columnsHtml)
  }
}

// 获得操作列的html
function getOptHtml(element, editable, columnsHtml) {
  const backtrack = element.backtrack
  const isBacktrack = backtrack && backtrack.isBacktrack ? true :  false
  if (editable || isBacktrack) {
    const btnEdit = editable ? `<el-button type="danger" size="mini" circle icon="el-icon-delete" title="删除" @click="handle${element.componentName}Remove(scope.row, scope.$index)"></el-button>` : ''
    let btnBacktrack = ''
    if (isBacktrack) {
      btnBacktrack = getBacktrackHtml(backtrack)
    }
    columnsHtml.push(`
      <el-table-column label="操作" width="60" align="center">
        <template slot-scope="scope">
          ${btnEdit}
          ${btnBacktrack}
        </template>
      </el-table-column>`
    )
  }
}

// 获取回溯的html
function getBacktrackHtml(backtrack) {
  const btnBacktrack = `
  <el-button 
    type="primary" 
    size="mini" 
    circle 
    icon="el-icon-coin" 
    title="查看数据回溯" 
    @click='handleViewBackTrack(scope.row, ${JSON.stringify(backtrack)})'>
  </el-button>
  `
  return btnBacktrack
}